/*
 * @Author: tcosfish
 * @Date: 2022-08-03 10:50:25
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-19 17:02:46
 * @FilePath: \loadFile\src\database\RyDataBase\index.ts
 */

// * RyDataBase 目前的作用就是
// * 1. 查询数据
// * 2. 将数据添加到数据库对应数据表中

import {
  DataSource,
  DataSourceOptions,
  Like,
  EntityTarget,
  ObjectLiteral,
  In,
} from "typeorm"
import { DataSourceConfig } from "@/config/database.config"
import { RecordView } from "../views/Record.view"

class RyDataBase {
  public instance: DataSource
  constructor(options: DataSourceOptions) {
    this.instance = new DataSource(options)
  }

  // 初始化
  public async init() {
    if (!ry_database.instance.isInitialized) {
      this.instance = await this.instance.initialize()
    }
    return this
  }

  // 利用 like 模糊搜索数据
  public async getData<T extends EntityTarget<ObjectLiteral>>(
    like: string,
    showCols: string[],
    QueryView: T
  ) {
    const result = await this.instance
      .getRepository(QueryView)
      .createQueryBuilder("view")
      .select(showCols)
      .where({ code: Like(like) })
      .getRawMany()
    return result
  }

  // 利用 in 获取数据
  public async getDataByIn<T extends EntityTarget<ObjectLiteral>>(
    indexCol: string[],
    QueryView: T
  ) {
    const result = await this.instance
      .getRepository(QueryView)
      .createQueryBuilder("view")
      .where({ code: In([...indexCol]) })
      .getMany()
    return result
  }

  getInstance() {
    return this.instance
  }
}

const ry_database = new RyDataBase(DataSourceConfig)

export default ry_database
